"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDragSort = useDragSort;

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _jsxRuntime = require("react/jsx-runtime");

var _proUtils = require("@ant-design/pro-utils");

var _reactSortableHoc = require("react-sortable-hoc");

var _index = require("./index");

var _excluded = ["className", "style"];

function useDragSort(props) {
  var _props$dataSource = props.dataSource,
      dataSource = _props$dataSource === void 0 ? [] : _props$dataSource,
      onDragSortEnd = props.onDragSortEnd,
      dragSortKey = props.dragSortKey; // 拖拽排序相关逻辑

  var SortableItem = (0, _reactSortableHoc.SortableElement)(function (p) {
    return (0, _jsxRuntime.jsx)("tr", (0, _objectSpread2.default)({}, p));
  });
  var SortContainer = (0, _reactSortableHoc.SortableContainer)(function (p) {
    return (0, _jsxRuntime.jsx)("tbody", (0, _objectSpread2.default)({}, p));
  });
  /* istanbul ignore next */

  var handleSortEnd = (0, _proUtils.useRefFunction)(function (params) {
    /* istanbul ignore next */
    var newDataSource = (0, _index.sortData)(params, dataSource);
    /* istanbul ignore next */

    if (newDataSource && onDragSortEnd) {
      /* istanbul ignore next */
      onDragSortEnd(newDataSource);
    }
  });
  var DraggableContainer = (0, _proUtils.useRefFunction)(function (p) {
    return (0, _jsxRuntime.jsx)(SortContainer, (0, _objectSpread2.default)({
      useDragHandle: true,
      disableAutoscroll: true,
      helperClass: "row-dragging",
      onSortEnd: handleSortEnd
    }, p));
  });
  var DraggableBodyRow = (0, _proUtils.useRefFunction)(function (p) {
    var DraggableBodyRowClassName = p.className,
        DraggableBodyRowStyle = p.style,
        restProps = (0, _objectWithoutProperties2.default)(p, _excluded); // function findIndex base on Table rowKey props and should always be a right array index

    var index = dataSource.findIndex(function (item) {
      var _props$rowKey;

      return item[(_props$rowKey = props.rowKey) !== null && _props$rowKey !== void 0 ? _props$rowKey : 'index'] === restProps['data-row-key'];
    });
    return (0, _jsxRuntime.jsx)(SortableItem, (0, _objectSpread2.default)({
      index: index
    }, restProps));
  });
  var components = props.components || {};

  if (dragSortKey) {
    var _props$components;

    components.body = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, ((_props$components = props.components) === null || _props$components === void 0 ? void 0 : _props$components.body) || {}), {}, {
      wrapper: DraggableContainer,
      row: DraggableBodyRow
    });
  }

  return {
    components: components
  };
}